package project.pianpian.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import project.pianpian.mapper.UserMapper;

/**
 * description:
 * author :万霁初
 * date :2022/12/25 21:32
 **/
@Configuration
public class WebMVCConfig implements WebMvcConfigurer {
    @Autowired
    UserMapper userMapper;

    //获取存储路径,从properties里拿
    @Value("${cover-save-path}")
    String coverPath;
    @Value("${video-save-path}")
    String videoPath;
    @Value("${demo-save-path}")
    String demoPath;

    //解决跨域
    @Override
    public void addCorsMappings(CorsRegistry corsRegistry){
        corsRegistry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

    //拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //无token时拦截，除了登陆注册
        registry.addInterceptor(new LoginInterceptor(userMapper))
                .excludePathPatterns("/main/login","/main/register")//要放行的页面
                .addPathPatterns("/**");//要拦截的页面
    }

    //添加路径
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //addResourceHandler("/covers/**")表示凡事以 /covers/ 路径发起请求的，按照 addResourceLocations("covers:"+coverPath)的路径进行映射
        registry.addResourceHandler("/covers/**").addResourceLocations("covers:"+videoPath);
        registry.addResourceHandler("/videos/**").addResourceLocations("videos:"+videoPath);
        registry.addResourceHandler("/demos/**").addResourceLocations("demos:"+demoPath);
    }
}
